package utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Date:2022/2/28
 * Author:ybc
 * Description:
 */
public class JDBCUtils {

    private static DataSource dataSource;

    static {
        try {
            //创建Properties对象
            Properties prop = new Properties();
            //获取jdbc.properties文件的输入流
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            //将jdbc.properties文件的内容加载到内存中
            prop.load(is);
            //通过druid数据源的工厂类获取数据源
            // 注意：保证jdbc.properties中的键一定要和DruidDataSource中相应属性名一致
            dataSource = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void closeConnection(Connection connection){
        if(connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
